package com.antgroup.seckill.business.goods.controller;

import com.antgroup.seckill.business.common.vo.request.GoodsQueryRequest;
import com.antgroup.seckill.business.common.vo.request.GoodsRequest;
import com.antgroup.seckill.business.common.vo.request.UpdateGoodsRequest;
import com.antgroup.seckill.business.common.vo.response.GoodsDetailVo;
import com.antgroup.seckill.business.common.vo.response.GoodsVo;
import com.antgroup.seckill.business.common.vo.response.RespBean;
import com.antgroup.seckill.business.goods.model.User;
import com.antgroup.seckill.business.goods.service.IGoodsService;
import com.antgroup.seckill.business.goods.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.antgroup.seckill.business.common.enums.RespBeanEnum.NOT_LOGIN;

/**
 * @author wangxy
 * @date 2024/7/27 15:18
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 跳转到商品页面
     *
     * @param session
     * @param model
     * @param userCookie
     * @return
     */
  /*  @RequestMapping("/toList")
    public String toList(HttpServletRequest request, HttpServletResponse response, Model model, @CookieValue("userCookie") String userCookie) {
        if(StringUtils.isEmpty(userCookie)) {
            return "login";
        }
        //利用了redis以后就不从session中获取用户信息了
       // User user = (User)session.getAttribute(userCookie);

        User user = iUserService.getUserByCookie(request, response, userCookie);
        if(Objects.isNull(user)) {
            return "login";
        }
        model.addAttribute("user",user);
        return "goodsList";
    }*/


    /**
     * 缓存整个页面(缓存整个页面，效率也不行，例如js文件，html传递个后端也耗时间)，这是第一种方式
     * <p>
     * 跳转到商品页面,商品页面缓存到redis
     * 用前置获取User方式然后去详情页面
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/toGoods", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toGoods(Model model, User user, HttpServletRequest request,
                          HttpServletResponse response) {
        if (Objects.isNull(user)) {
            return "login";
        }

        //先去缓存取，如果不为空直接返回页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String goodsListHtml = (String) valueOperations.get("goodsList");
        if (StringUtils.isNotEmpty(goodsListHtml)) {
            return goodsListHtml;
        }

        List<GoodsVo> goodsVos = iGoodsService.queryAllGoods();
        model.addAttribute("user", user);
        model.addAttribute("goodsVoList", goodsVos);

        if (CollectionUtils.isEmpty(goodsVos)) {
            return "goodsNot";
        }

        //手动渲染页面，在塞进redis,然后返回
        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());

        goodsListHtml = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);

        if (StringUtils.isNotEmpty(goodsListHtml)) {
            valueOperations.set("goodsList", goodsListHtml, 60, TimeUnit.SECONDS);

        }
        //return "goodsList";
        return goodsListHtml;

    }

    /**
     * 跳转到商品详情页面,商品详情页面缓存到redis(缓存整个页面，效率也不行，例如js文件，html传递个后端也耗时间)
     * <p>
     * 用前置获取User方式然后去详情页面
     *
     * @param model
     * @param user
     * @return
     */
    @GetMapping(value = "/toGoodsDetail", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toGoodsDetail(Model model, User user, @RequestParam(required = true) String goodsId,
                                HttpServletRequest request, HttpServletResponse response) {
        if (Objects.isNull(user)) {
            return "login";
        }

        //先去缓存中取，如果有直接返回
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String goodsDetailHtml = (String) valueOperations.get("goodsDetail:" + goodsId);
        if (StringUtils.isNotEmpty(goodsDetailHtml)) {
            return goodsDetailHtml;
        }


        GoodsVo goodsDetail = iGoodsService.queryGoodsByGoodsId(goodsId);

        //返回秒杀状态 0秒杀为开始  1表示秒杀进行中  2表示秒杀已经结束
        Date startTime = goodsDetail.getStartTime();
        Date endTime = goodsDetail.getEndTime();
        Date nowTime = new Date();
        int googsSeckillStatus;
        int reaminSeconds = 0;
        if (nowTime.before(startTime)) {
            googsSeckillStatus = 0;
            reaminSeconds = (int) (startTime.getTime() - nowTime.getTime()) / 1000;
        } else if (nowTime.after(endTime)) {
            googsSeckillStatus = 2;
        } else {
            googsSeckillStatus = 1;
        }


        //秒杀到记时返回
        model.addAttribute("user", user);
        model.addAttribute("reaminSeconds", reaminSeconds);
        model.addAttribute("googsSeckillStatus", googsSeckillStatus);
        model.addAttribute("goodsDetail", goodsDetail);

        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());

        goodsDetailHtml = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);
        if (StringUtils.isNotEmpty(goodsDetailHtml)) {
            //塞进缓存
            valueOperations.set("goodsDetail:" + goodsId, goodsDetailHtml, 60, TimeUnit.SECONDS);


        }
        //return "goodsDetail";
        return goodsDetailHtml;
    }


    /**
     * 商品详情也静态化处理(第二种方式)
     * <p>
     * 用前置获取User方式然后去详情页面
     *
     * @param user
     * @return
     */
    @GetMapping("/toStaticGoodsDetail")
    @ResponseBody
    public RespBean toStaticGoodsDetail(User user, @RequestParam(required = true) String goodsId) {

        if (Objects.isNull(user)) {
            return RespBean.error(NOT_LOGIN);
        }

        GoodsVo goodsDetail = iGoodsService.queryGoodsByGoodsId(goodsId);

        //返回秒杀状态 0秒杀为开始  1表示秒杀进行中  2表示秒杀已经结束
        Date startTime = goodsDetail.getStartTime();
        Date endTime = goodsDetail.getEndTime();
        Date nowTime = new Date();
        int googsSeckillStatus;
        int reaminSeconds = 0;
        if (nowTime.before(startTime)) {
            googsSeckillStatus = 0;
            reaminSeconds = (int) (startTime.getTime() - nowTime.getTime()) / 1000;
        } else if (nowTime.after(endTime)) {
            googsSeckillStatus = 2;
        } else {
            googsSeckillStatus = 1;
        }
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setUser(user);
        goodsDetailVo.setGoodsVo(goodsDetail);
        goodsDetailVo.setGoogsSeckillStatus(googsSeckillStatus);
        goodsDetailVo.setReaminSeconds(reaminSeconds);

        return RespBean.success(goodsDetailVo);
    }

    /**
     * 添加商品
     *
     * @param user
     * @return
     */
    @PostMapping("/saveGoods")
    @ResponseBody
    public RespBean saveGoods(User user, @RequestBody @Valid GoodsRequest request) {
        if (Objects.isNull(user)) {
            return RespBean.error(NOT_LOGIN);
        }

        iGoodsService.saveGoods(request,user);
        return RespBean.success();
    }

    /**
     * 更新商品
     *
     * @param user
     * @return
     */
    @PostMapping("/updateGoods")
    @ResponseBody
    public RespBean updateGoods(User user, @RequestBody UpdateGoodsRequest request) {
        if (Objects.isNull(user)) {
            return RespBean.error(NOT_LOGIN);
        }

        iGoodsService.updateGoods(request);
        return RespBean.success();
    }

    /**
     * 删除商品
     *
     * @param user
     * @return
     */
    @GetMapping("/deleteGoods")
    @ResponseBody
    public RespBean deleteGoodsById(User user,  @RequestParam(required = true) String goodsId) {
        if (Objects.isNull(user)) {
            return RespBean.error(NOT_LOGIN);
        }

        iGoodsService.deleteGoodsById(goodsId);
        return RespBean.success();
    }


    /**
     * 查询商品
     *
     * @param user
     * @return
     */
    @PostMapping("/queryGoods")
    @ResponseBody
    public RespBean queryGoods(User user,  @RequestBody GoodsQueryRequest request) {
        if (Objects.isNull(user)) {
            return RespBean.error(NOT_LOGIN);
        }

        List<GoodsVo> goodsVoList = iGoodsService.queryGoods(request);
        return RespBean.success(goodsVoList);
    }



}
